package com.jack.atomic;

import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStampedReferenceTest {
    static AtomicStampedReference  atomicStampedReference = new AtomicStampedReference(1,0);

    public static void main(String[] args) {
        Thread main = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("操作线程" + Thread.currentThread() +",初始值 a = " + atomicStampedReference.getReference());
                int stamp = atomicStampedReference.getStamp();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boolean isCASSuccess = atomicStampedReference.compareAndSet(1, 2, stamp, stamp + 1);
                System.out.println("操作线程" + Thread.currentThread() +",CAS操作结果: " + isCASSuccess +" ,值 = "+ atomicStampedReference.getReference());

            }
        },"主线程");

        Thread other = new Thread(new Runnable() {
            @Override
            public void run() {
                Thread.yield();// 确保thread-main 优先执行˚
                boolean increment = atomicStampedReference.compareAndSet(1, 2, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
                System.out.println("操作线程" + Thread.currentThread() +",【increment】"+ increment+" ,值 = "+ atomicStampedReference.getReference());
                boolean decrement = atomicStampedReference.compareAndSet(2, 1, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
                System.out.println("操作线程" + Thread.currentThread() +",【decrement】"+ decrement+" ,值 = "+ atomicStampedReference.getReference());
            }
        },"干扰线程");
        main.start();
        other.start();
    }


}
